<?php
declare (strict_types = 1);

namespace app\admin\controller;
use app\admin\validate\AdminValidate;
use app\admin\validate\AdminValidate2;
use app\middleware\Auth;
use app\middleware\AuthOperate;
use think\facade\Db;
class Index
{
    /**

    --
    -- 表的结构 `admin`
    --

    CREATE TABLE `admin` (
    `admin_id` int NOT NULL COMMENT 'id',
    `admin_name` varchar(15) DEFAULT NULL COMMENT '账户',
    `admin_head` varchar(255) DEFAULT NULL COMMENT '头像',
    `admin_password` varchar(255) DEFAULT NULL COMMENT '密码',
    `admin_status` mediumint DEFAULT '0' COMMENT '状态0:正常，1封禁',
    `error_num` int NOT NULL DEFAULT '0' COMMENT '登录错误次数',
    `error_time` date NOT NULL DEFAULT '1970-01-01' COMMENT '错误日期',
    `admin_create_time` datetime DEFAULT NULL COMMENT '创建时间'
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

    --
    -- 转存表中的数据 `admin`
    --

    INSERT INTO `admin` (`admin_id`, `admin_name`, `admin_head`, `admin_password`, `admin_status`, `error_num`, `error_time`, `admin_create_time`) VALUES
    (1, 'admin', 'https://blqcs.yyuebd.com/storage/uploads/20221124/c2eb2ccfe9aeee92d0a1ee0127d2f1d1.jpg', '$2y$10$4riNK0pzHLM9jBLPuuMjP.8GpCI4HtsHQaYiyTcRIs/dTYyBjsm.m', 0, 0, '2022-12-28', '2022-08-24 18:13:40');

    --
    -- 转储表的索引
    --

    --
    -- 表的索引 `admin`
    --
    ALTER TABLE `admin`
    ADD PRIMARY KEY (`admin_id`),
    ADD UNIQUE KEY `admin_name` (`admin_name`);

    --
    -- 在导出的表使用AUTO_INCREMENT
    --

    --
    -- 使用表AUTO_INCREMENT `admin`
    --
    ALTER TABLE `admin`
    MODIFY `admin_id` int NOT NULL AUTO_INCREMENT COMMENT 'id', AUTO_INCREMENT=2;
    COMMIT;

     */
    protected $middleware = [
        Auth::class =>[ 'except'=>['login','getUser'] ],//except：除了之外
        AuthOperate::class =>[ 'except'=>['login','getUser','getInfo'] ]
    ];
    protected function getUser($username){
        return  Db::table("admin")->where(['admin_name'=>trim($username)])->find();
    }
    public function login()
    {
        $max_error_num = 5;
        $data = request()->param();
        //$data = ['username'=>'admin','password'=>'123456789'];
        $AdminValidate =  new AdminValidate();
        if($AdminValidate->scene('admin_login')->check($data)){
            $user = $this->getUser($data['username']);
            if(empty($user)){//不存在该用户
                return json(['status'=>500,'msg'=>'当前用户不存在！']);
            }else if($user['admin_status']){//当前用户被封禁
                return json(['status'=>500,'msg'=>'当前用户被封禁！']);
            }else if($user['error_num']>=$max_error_num&&$user['error_time']==date("Y-m-d")){//连续输错密码次数过多
                return json(['status'=>500,'msg'=>'连续输错密码'.$max_error_num.'次密码,明日再试！']);
            }else{
                $check = checkPassword((string)$data['password'],(string)$user['admin_password']);
                if($check['status']==200){//验证通过
                    $status = 200;
                    $msg = "登录成功！";
                    $username = $data['username'];
                    $token = signToken($user['admin_id']);
                    Db::table("admin")->where(['admin_name'=>trim($data['username']),'admin_status'=>0])->update([
                        'error_time'=>date('Y-m-d'),
                        'error_num'=>0
                    ]);
                }else{
                    if($user['error_time']!=date("Y-m-d")){
                        Db::table("admin")->where(['admin_name'=>trim($data['username']),'admin_status'=>0])->update([
                            'error_num'		=>	1,
                            'error_time'	=>	date('Y-m-d')
                        ]);
                    }else{
                        Db::table("admin")->where(['admin_name'=>trim($data['username']),'admin_status'=>0])->update([
                            'error_num'		=>	Db::raw('error_num+1'),
                            'error_time'	=>	date('Y-m-d')
                        ]);
                    }
                    $user2 = $this->getUser($data['username']);
                    $status = 500;
                    $msg = $user2['error_num']<$max_error_num?"密码错误！您还可以输入" . ($max_error_num - $user2['error_num']) .'次。':'连续输错密码'.$max_error_num.'次密码,明日再试！';
                    $username = '';
                    $token ='';
                }
                return json(['status'=>$status,'msg'=>$msg,'user'=>$username,'token'=>$token]);
            }
        }else{
            return json(['status'=>500,'msg'=>$AdminValidate->getError()]);
        }
    }
    public function getInfo(){
        $user = Db::table("admin")->where(['admin_id'=>checkToken(request()->header('token'))['data']->uid])
            ->filter(function ($user){
                $user['roles'] = 'admin';
                return $user;
            })
            ->field('admin_id,admin_name,admin_head')
            ->find();
        return json(['status'=>200,'msg'=>'ok','data'=>$user]);
    }
    public function headUpload(){
        $size = 2097152;//2M
        $fileType = "jpg,jpeg,png,gif";
        $headFile = fileUpload($size,$fileType);
        return json($headFile);
    }
    public function getAdmin(){
        $data = request()->param();
        $page = (int)$data['page'];
        $limit = (int)$data['limit'];
        unset($data['page']);
        unset($data['limit']);
        $field = 'admin_id,admin_head,admin_name,admin_nickname,admin_status,admin_create_time';
        if($this->checkIsMaxAuth()){
            $admin_data = Db::table('admin')
                ->page($page,$limit)
                ->where($data)
                ->field($field)
                ->select();
            $total = Db::table('admin')
                ->where($data)
                ->count();
            return json(['status'=>200,'msg'=>'ok','data'=>$admin_data,'total'=>$total]);
        }else{
            $data['admin_id'] = checkToken(request()->header('token'))['data']->uid;
            $admin_data = Db::table('admin')
                ->page($page,$limit)
                ->where($data)
                ->field($field)
                ->select();
            $total = Db::table('admin')
                ->where($data)
                ->count();
            return json(['status'=>200,'msg'=>'ok','data'=>$admin_data,'total'=>$total]);

        }

    }
    //判断是否是最高管理员【是否存在group_id = 1】
    private function checkIsMaxAuth(){
        $group_id_arr =  Db::table('think_auth_group_access')->where('uid',checkToken(request()->header('token'))['data']->uid)->column('group_id');
        if(in_array(1,$group_id_arr)){
            return true;
        }else{
            return false;
        }
    }
    public function createAdmin(){
        $data = request()->param();
        $AdminValidate2 = new AdminValidate2();
        if(!$AdminValidate2->check($data)){
            return json(['status'=>500,'msg'=>$AdminValidate2->getError()]);
        }
        unset($data['admin_password2']);
        $admin_name =  Db::table("admin")->where("admin_name",$data['admin_name'])->find();
        if(!empty($admin_name)){
            return json(['status'=>500,'msg'=>'用户已存在！']);
        }
        //头像变量没有设置 和 头像为空
        if(!isset($data['admin_head'])||empty($data['admin_head'])){
            //默认头像
            $data['admin_head'] = 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png';
        }
        $set_password = set_password((string)$data['admin_name'],(string)$data['admin_password']);
        $new =   array_merge($data,$set_password);
//            var_dump($new);
        $res = Db::table('admin')->insert($new);
        if($res){
            return json(['status'=>200,'msg'=>'新增成功']);
        }else{
            return json(['status'=>500,'msg'=>'新增失败']);
        }
    }
    public function updateAdmin(){
        $data = request()->param();
        $adminId = $data['admin_id'];
        if(!$this->checkIsMaxAuth()){//若不是超级管理员
            //且通过模拟请求来修改其他人信息，则返回
            if(checkToken(request()->header('token'))['data']->uid != $adminId){
                return json(['status'=>500,'msg'=>'抱歉,只能修改自己的信息']);
            }
        }
        if(isset($data['admin_password'])){
            $AdminValidate2 = new AdminValidate2();
            if(!$AdminValidate2->scene('update_admin')->check($data)){
                return json(['status'=>500,'msg'=>$AdminValidate2->getError()]);
            }
            $data['admin_password'] =  password_hash((string)$data['admin_password'],PASSWORD_DEFAULT);
        }
        unset($data['admin_password2']);
        unset($data['admin_nickname']);
        $update = Db::table('admin')->where('admin_id',$adminId)->update($data);
        if($update){
            return json(['status'=>200,'msg'=>"修改成功"]);
        }else{
            return json(['status'=>500,'msg'=>"修改失败"]);
        }
    }
    public function delAdmin(){
        $data = request()->param();
        $adminId = $data['admin_id'];

        $adminHeadUrl = Db::table('admin')->where('admin_id', $adminId)->value('admin_head');

        // 判断这个头像的url是否是当前域名的url
        if ($_SERVER['HTTP_HOST'] == parse_url($adminHeadUrl, PHP_URL_HOST)) {
            $delData = cutOutUrl($adminHeadUrl);
            $delUrl = $delData['del_url'];

            if (file_exists($delUrl)) {
                unlink($delUrl);
            }

            $deleteResult = Db::table('admin')->where('admin_id', $adminId)->delete();

            if ($deleteResult) {
                return json(['status' => 200, 'msg' => "删除成功"]);
            } else {
                return json(['status' => 500, 'msg' => "删除失败"]);
            }
        } else {
            $deleteResult = Db::table('admin')->where('admin_id', $adminId)->delete();

            if ($deleteResult) {
                return json(['status' => 200, 'msg' => "删除成功"]);
            } else {
                return json(['status' => 500, 'msg' => "删除失败"]);
            }
        }
    }
    public function updateAdminStatus(){
        $data = request()->param();
        switch ($data['admin_status']){
            case 0: $admin_status = 1;$msg='禁用';break;
            case 1: $admin_status = 0;$msg='启用';break;
        }
        $status = Db::table('admin')->where('admin_id',$data['admin_id'])->update(['admin_status'=>$admin_status]);
        if($status){
            return json(['status'=>200,'msg'=>$msg."成功"]);
        }else{
            return json(['status'=>500,'msg'=>$msg."失败"]);
        }
    }
    //获取所有角色，以便给管理员添加角色
    public function getHandleAuthRole(){
        $data = request()->param();
        //获取角色
        $think_auth_role = Db::table('think_auth_group')->select();
        //获取当前管理用户扮演哪些角色
        $group_id = Db::table('think_auth_group_access')->where('uid',$data['uid'])->column('group_id');
        $group_access = Db::table('think_auth_group')->whereIn('id',$group_id)->select();
        return json(['status'=>200,'role'=>$think_auth_role,'group_access'=>$group_access]);
    }
    //给用户添加角色
    public function addHandAuthRole(){
        $data = request()->param();
        Db::table('think_auth_group_access')->where('uid',$data[0]['uid'])->delete();
        if($data[0]['group_id'] != -1 ){//若提交为-1，则是清空所有权限
            $res = Db::table('think_auth_group_access')->insertAll($data);
        }
        if($res){
            success('角色分配');
        }else{
            fail('角色分配');
        }
    }
    ///////////////////////////////
    public function updatePassword(){
        $data = request()->param();
        $user = Db::table("admin")->where(['admin_id'=>checkToken(request()->header('token'))['data']->uid,'admin_status'=>0])->find();
        if(empty($data['nickname'])){
            $data['nickname'] = $user['admin_name'];
        }
        $check = checkPassword((string)$data['old_password'],(string)$user['admin_password']);
        if($check['status']==200){
            $res = Db::table("admin")->where('admin_id',$user['admin_id'])->update([
                'admin_password'=>password_hash((string)$data['new_password'],PASSWORD_DEFAULT),
                'admin_name'=>$data['nickname']
            ]);
            return $res?(array('status'=>200,'msg'=>"修改成功")):(array('status'=>500,'msg'=>"修改失败"));
        }else{
            return json(['status'=>500,"msg"=>"旧密码不匹配，无法进行修改！"]);
        }
    }

}
